<?php
/**
 * Created by PhpStorm.
 * User: plume
 * Date: 2017/11/14
 * Time: 15:45
 */

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Libraries\HTTPHandler;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //微信企业号登陆
    public function wxqyhLogin(Request $request){
        $code = $request->input("code");
        $qyh_access_token = HTTPHandler::getAccessTokenQYH();
        $get_user_id_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$qyh_access_token.'&code='.$code;
        $res = HTTPHandler::http_get_data($get_user_id_url);
        Log::info($res);
        $json_obj = json_decode($res,true);

        if($json_obj['errcode'] == '0' && !isset($json_obj['UserId'])){
            return view('errors.error', ['info'=>"用户为非企业成员"]);
        }
        if($json_obj['errcode'] != '0'){
            return view('errors.error', ['info'=>"用户信息获取失败"]);
        }

        $userid = $json_obj['UserId'];

        $user = User::where('qyh_userid', $userid)->first();
        if(empty($user)) {
            return view('errors.error', ['info'=>"数据未同步，请稍后再试"]);
        }
        $user->api_token = str_random(16);
        $user->api_token_expire_at = date('Y-m-d H:i:s', time()+12*3600);
        $user->save();
        setcookie("api_token", $user->api_token, time()+12*3600, '/');
        if($user->status == User::STATUS_DISABLED){
            return redirect("/apply");
        }
        return redirect("/index");
    }

    public function getUsers(Request $request){
        $user = Auth::user();
        $name = $request->input('name');
        $users = User::where(function($query) use($name){
            if (!empty($name)) {
                $query->where('nickname', 'like', '%' . $name . '%');
            }
        })
            ->where('id', '<>', $user->id)
            ->where('status', User::STATUS_ENABLED)
            ->get();
        foreach($users as $user){
            $user->avatar = urldecode($user->avatar);
        }
        return ['code'=>0, 'data'=>['users'=>$users]];
    }
}